
#coding:utf-8
# 导入蓝图的视图
from . import upload
import base64
import face_recognition
import pickle
from bson import Binary
from flask import request, render_template, flash
from faces import db
from faces.models import UserForm, UserInfo


@upload.route("/", methods=["GET", "POST"])
def hello():
    forms = UserForm()

    users = UserInfo.query.all()
    if request.method == "POST":
        imgdata = request.form.get("myimg")
        id = request.form.get("id")
        name = request.form.get("name")
        id = str(id)
        path = r"faces/static/photo/" + id + ".jpg"
        img_base64_data = base64.b64decode(imgdata)
        print(id)
        with open(path, "wb") as f:
            f.write(img_base64_data)

        # 读取图片的过程其实就是把base64转为ndarray
        imgfile = face_recognition.load_image_file(path)

        face_code = face_recognition.face_encodings(imgfile)[0]
        # 注意: 得到的face_code 一定是ndarray类型的数据
        if face_code != []:

            # mongodb或是mysql 不能直接储存ndarray数据,利用pickle模块
            # pickle模块中的dumps方法可以把特殊类型转为python类型
            # faces_data = pickle.dumps(face_code[0], protocol=-1)

            # print(type(faces_data))
            # 这个数据一定要经过转换，才可以存储到数据库中
            binary_data = Binary(pickle.dumps(face_code, protocol=-1),
                                 subtype=128)
            try:
                new_user = UserInfo(userid=id,
                                    username=name,
                                    userphoto=binary_data)
                db.session.add(new_user)
                db.session.commit()
                return "成功"
                flash("添加员工成功")
            except Exception as e:

                db.session.rollback()
                return "fail"
                flash('添加失败')
    return render_template("index.html", users=users, form=forms)